package com.myecl.poker.communication;
import java.io.*;
import java.net.Socket;

import com.myecl.poker.view.View;


public class Client {
	 private View view;

    public Client(String name) {
    	 try {       
             final Socket socket = new Socket("localhost",9999);

             ObjectOutputStream objectOutput = new ObjectOutputStream(socket.getOutputStream());
             objectOutput.flush();
             view = new View(name, new ClientConnector(objectOutput));
             objectOutput.writeObject(new PlayerInformation(name));
             
             
             (new Thread() {   	
                 @Override
                 public void run() {
                	 try {  
                		 checkViewUpdate(new ObjectInputStream(socket.getInputStream()));
                	 } catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
             }).start();

         } catch (Exception e) {
             e.printStackTrace();
         }
    }   

    private  void checkViewUpdate(ObjectInputStream objectInput) {
    	 while (true) {
    		 try {
	    		 ViewData viewData = (ViewData) objectInput.readObject();
	    		 view.update(viewData);
    		 } catch(Exception e) {
            	 e.printStackTrace();
    		 }
    	 }
    }
}
